package com.dhh.sky.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.devspark.appmsg.AppMsg;
import com.dhh.sky.model.SkyDriveObject;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.Gravity;

public class CUtil {
	public static String buildFileName(SkyDriveObject obj){
		String oname = obj.getName();
		String name = obj.getId();
		String ext = getFileExtesion(oname);	
		
		return ext!=null ? name+"."+ext : name;
		
	}
	
	public static Message buildMessage(){
		Message msg = new Message();
		Bundle data = new Bundle();
		msg.setData(data);
		return msg;
	}
	
	public static String getFileExtesion(String fileName){
    	String ext = null;
		if(fileName ==null || fileName.length()==0){
			return ext;
		}
    	int dotIndex=fileName.lastIndexOf('.');
    	if(dotIndex>=0) {
    		ext=fileName.substring(dotIndex+1,fileName.length());
    	}
    	
    	return ext;
    }
	
	public static String getFilePreName(String fileName){
    	String name = fileName;
		if(fileName ==null || fileName.length()==0){
			return name;
		}
    	int dotIndex=fileName.lastIndexOf('.');
    	if(dotIndex>0) {
    		name=fileName.substring(0,dotIndex);
    	}
    	
    	return name;
    }
	
	private static int calculateSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
	    final int height = options.outHeight;
	    final int width = options.outWidth;
	    int size = 1;

	    if (height > reqHeight || width > reqWidth) {
	        if (width > height) {
	        	size = Math.round((float)height / (float)reqHeight);
	        } else {
	        	size = Math.round((float)width / (float)reqWidth);
	        }
	    }
	    return size;
	}
	
	public static Bitmap decodeBitmap(File file, int reqWidth, int reqHeight) {
		Bitmap bitmap = null;
		try{
			InputStream is = new FileInputStream(file);
		    BitmapFactory.Options options = new BitmapFactory.Options();
		    options.inPreferredConfig = Bitmap.Config.RGB_565;
		    options.inJustDecodeBounds = true;
		    options.inInputShareable = true; 		    
		    options.inSampleSize = calculateSize(options, reqWidth, reqHeight);
		    bitmap =BitmapFactory.decodeStream(is,null,options);
		    bitmap.recycle();
		    is.close();
		}catch(Exception e){
			Log.e(Constant.TAG, e.getMessage(),e);
		}
		
		return bitmap;
	}
	
	public static boolean isMarketInstalled(Context context){
		boolean flag = true;
		try{
			context.getPackageManager().getApplicationInfo("com.android.vending", 0 );
		}catch(Exception e){
			flag = false;
		}
		return flag;
	}
	
	public static boolean isNetworkAvailable(Context context){
		boolean isAvailable = false;
		try{
			ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
			if (activeNetwork!=null && activeNetwork.isConnected()) {				
				return true;
			}
		}catch(Exception e){
			Log.e(Constant.TAG, e.getMessage(), e);
		}
		return isAvailable;
	}
	
	public static List<String> getCameraImages(Context context) {
		//TODO for HTC the images is saved in /DCIM/100MEDIA, so need to check it.
		String CAMERA_IMAGE_BUCKET_NAME = Environment.getExternalStorageDirectory().toString() + "/DCIM/Camera";
		String CAMERA_IMAGE_BUCKET_ID = String.valueOf(CAMERA_IMAGE_BUCKET_NAME.toLowerCase().hashCode());
		
	    final String[] projection = { MediaStore.Images.Media.DATA };
	    final String selection = MediaStore.Images.Media.BUCKET_ID + " = ?";
	    final String[] selectionArgs = { CAMERA_IMAGE_BUCKET_ID };
	    final Cursor cursor = context.getContentResolver().query(Images.Media.EXTERNAL_CONTENT_URI, 
	            projection, 
	            selection, 
	            selectionArgs, 
	            null);
	    ArrayList<String> result = new ArrayList<String>(cursor.getCount());
	    if (cursor.moveToFirst()) {
	        final int dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	        do {
	            final String data = cursor.getString(dataColumn);
	            result.add(data);
	        } while (cursor.moveToNext());
	    }
	    cursor.close();
	    return result;
	}
	
	public static boolean isFileExists(SkyDriveObject obj){
		return new File(Constant.SKYDRIVE_LOCAL_PATH+"/"+CUtil.buildFileName(obj)).exists();
	}
	
	public static void showToast(android.app.Activity activity,int message,AppMsg.Style style){
		AppMsg appMsg = AppMsg.makeText(activity, activity.getString(message), style);
		appMsg.setLayoutGravity(Gravity.BOTTOM);
		appMsg.show();
	}
	
	public static void showToast(android.app.Activity activity,String message,AppMsg.Style style){
		AppMsg appMsg = AppMsg.makeText(activity, message, style);
		appMsg.setLayoutGravity(Gravity.BOTTOM);
		appMsg.show();
	}
}
